<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-card>
      <el-form :model="queryParams" ref="queryForm" :inline="false" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出库状态" prop="orderStatus">
              <el-radio-group v-model="queryParams.orderStatus" @change="handleQuery">
                <el-radio-button label="all">
                  全部
                </el-radio-button>
                <el-radio-button v-for="item in wms_deliver_status" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="出库单号" prop="billsId">
              <el-input v-model="queryParams.billsId" placeholder="请输入出库单号" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库人" prop="outUserName">
              <el-input v-model="queryParams.outUserName" placeholder="请输入出库人姓名" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="复核时间" prop="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleDateChange"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 业务流程说明 -->
    <el-card class="mt20">
      <el-alert title="出库确认说明" type="info" :closable="false" class="mb8">
        <template #default>
          <div style="font-size: 13px; line-height: 22px;">
            <p>📋 <strong>出库确认流程：</strong>从已复核的出库单中查询待出库任务 → 执行出库确认 → 完成出库（扣减库存）</p>
            <p>📊 <strong>数据来源：</strong>出库任务来自出库主表中状态为2（已复核待出库）的单据</p>
            <p>✅ <strong>出库完成：</strong>状态更新为「已出库」（状态3），记录出库人员、时间，扣减库存</p>
            <p>⚠️ <strong>重要提示：</strong>出库确认后库存会真实扣减，请谨慎操作！确认后不可撤销</p>
            <p>📱 <strong>PDA操作：</strong>PDA出库确认后会直接修改数据库状态，系统同步显示最新状态</p>
            <p>🔢 <strong>状态说明：</strong>0-待拣货，1-已拣货待复核，2-已复核待出库，3-已出库，9-异常</p>
          </div>
        </template>
      </el-alert>

      <!-- 统计卡片 -->
      <el-row :gutter="15" class="mb8">
        <el-col :span="5">
          <el-card class="stat-card" @click.native="handleStatClick('')">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalTasks }}</div>
              <div class="stat-label">总任务数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="stat-card" @click.native="handleStatClick('2')">
            <div class="stat-item">
              <div class="stat-value pending">{{ statistics.pendingTasks }}</div>
              <div class="stat-label">待出库</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="stat-card" @click.native="handleStatClick('3')">
            <div class="stat-item">
              <div class="stat-value completed">{{ statistics.completedTasks }}</div>
              <div class="stat-label">已出库</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.todayOutTasks }}</div>
              <div class="stat-label">今日出库</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-truck" size="mini" @click="handleBatchDeliver"
            :disabled="multiple">批量出库</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleQuery">刷新</el-button>
        </el-col>
      </el-row>

      <!-- 出库确认表格 -->
      <el-table :data="taskList" @selection-change="handleSelectionChange" border
        height="calc(100vh - 580px)" style="width: 100%">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="expand" width="40">
          <template #default="{ row }">
            <div style="padding: 0 50px 20px 50px">
              <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
                <el-col :span="6"><span style="font-size: large">单据明细</span></el-col>
              </el-row>
              <el-table :data="row.detailData || []" border>
                <el-table-column show-overflow-tooltip type="index" label="行号" align="center" min-width="60"></el-table-column>
                <el-table-column show-overflow-tooltip prop="drugId" label="药品编码" align="center" min-width="120" />
                <el-table-column show-overflow-tooltip prop="drugName" label="药品名称" align="center" min-width="200" />
                <el-table-column show-overflow-tooltip prop="drugCd" label="生产厂家" align="center" min-width="150" />
                <el-table-column show-overflow-tooltip prop="drugBatchNo" label="批号" align="center" min-width="120" />
                <el-table-column show-overflow-tooltip prop="drugGg" label="规格" align="center" min-width="150" />
                <el-table-column show-overflow-tooltip prop="drugDw" label="单位" align="center" min-width="80" />
                <el-table-column show-overflow-tooltip prop="drugNum" label="应出数量" align="center" min-width="100" />
                <el-table-column show-overflow-tooltip prop="drugCheckNum" label="实出数量" align="center" min-width="100" />
                <el-table-column show-overflow-tooltip prop="locationCode" label="货位号" align="center" min-width="120" />
                <el-table-column show-overflow-tooltip prop="drugPd" label="生产日期" align="center" min-width="120" />
                <el-table-column show-overflow-tooltip prop="drugExp" label="有效期" align="center" min-width="120" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="billsID" label="出库单号" align="center" width="180"></el-table-column>
        <el-table-column show-overflow-tooltip prop="billsTypeName" label="单据类型" align="center" width="120"></el-table-column>
        <el-table-column show-overflow-tooltip prop="billsCdName" label="往来单位" align="center" min-width="200"></el-table-column>
        <el-table-column show-overflow-tooltip prop="totalPackages" label="总件数" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="totalQuantity" label="总数量" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip label="出库状态" align="center" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.stockStatus === '2'" type="warning">待出库</el-tag>
            <el-tag v-else-if="scope.row.stockStatus === '3'" type="success">已出库</el-tag>
            <el-tag v-else>-</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="pickingUserName" label="拣货人" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="reviewUserName" label="复核人" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="reviewTime" label="复核时间" align="center" width="160"></el-table-column>
        <el-table-column show-overflow-tooltip prop="outUserName" label="出库人" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="outTime" label="出库时间" align="center" width="160"></el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.stockStatus === '2'" type="success" size="small" @click="handleDeliver(scope.row)">出库确认</el-button>
            <el-button v-if="scope.row.stockStatus === '3'" type="info" size="small" @click="handleViewDetail(scope.row)">查看</el-button>
            <el-button v-if="scope.row.stockStatus === '3'" type="primary" size="small" @click="handlePrint(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="float: right; margin: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  finishStoreList,
  finishStoreDetail,
  deliverGoods
} from '@/api/storage/finishStore'

export default {
  name: 'DeliverConfirm',
  data() {
    return {
      total: 0,
      pageSize: 10,
      pageNum: 1,
      queryParams: {
        billsId: '',
        outUserName: '',
        orderStatus: 'all',
        startTime: null,
        endTime: null
      },
      dateRange: null,
      wms_deliver_status: [
        { label: '待出库', value: '2' },
        { label: '已出库', value: '3' },
        { label: '异常', value: '9' }
      ],
      taskList: [],
      multipleSelection: [],
      single: true,
      multiple: true,
      statistics: {
        totalTasks: 0,
        pendingTasks: 0,
        completedTasks: 0,
        todayOutTasks: 0
      }
    }
  },
  created() {
    this.handleQuery()
    this.loadStatistics()
  },
  methods: {
    // 查询
    handleQuery() {
      const params = {
        ...this.queryParams,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        type:'3',
      }
      finishStoreList(params).then(res => {
        this.taskList = res.rows || []
        this.total = res.total || 0
      }).catch(err => {
        this.$message.error('查询失败：' + err.message)
      })
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        billsId: '',
        outUserName: '',
        orderStatus: 'all',
        startTime: null,
        endTime: null
      }
      this.dateRange = null
      this.pageNum = 1
      this.handleQuery()
    },

    // 日期范围变化
    handleDateChange(value) {
      if (value && value.length === 2) {
        this.queryParams.startTime = value[0]
        this.queryParams.endTime = value[1]
      } else {
        this.queryParams.startTime = null
        this.queryParams.endTime = null
      }
    },

    // 统计卡片点击
    handleStatClick(status) {
      this.queryParams.orderStatus = status || 'all'
      this.pageNum = 1
      this.handleQuery()
    },

    // 加载统计数据
    loadStatistics() {
      finishStoreList({ orderStatus: 'all' }).then(res => {
        const data = res.rows || []
        this.statistics.totalTasks = data.filter(item => ['2', '3'].includes(item.stockStatus)).length
        this.statistics.pendingTasks = data.filter(item => item.stockStatus === '2').length
        this.statistics.completedTasks = data.filter(item => item.stockStatus === '3').length

        // 计算今日出库数量
        const today = new Date().toISOString().split('T')[0]
        this.statistics.todayOutTasks = data.filter(item => {
          return item.stockStatus === '3' && item.outTime && item.outTime.startsWith(today)
        }).length
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 出库确认操作
    handleDeliver(row) {
      this.$confirm('确认出库操作吗？出库后将扣减库存，无法撤销！', '重要提示', {
        confirmButtonText: '确认出库',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        deliverGoods(row.billsID).then(res => {
          this.$message.success(res.msg || '出库成功')
          this.handleQuery()
          this.loadStatistics()
        }).catch(err => {
          this.$message.error('出库失败：' + err.message)
        })
      }).catch(() => {
        this.$message.info('已取消出库')
      })
    },

    // 批量出库
    handleBatchDeliver() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要出库的单据')
        return
      }
      this.$confirm(`确认批量出库选中的 ${this.multipleSelection.length} 个单据吗？出库后将扣减库存，无法撤销！`, '重要提示', {
        confirmButtonText: '确认出库',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const promises = this.multipleSelection.map(item => deliverGoods(item.billsID))
        Promise.all(promises).then(() => {
          this.$message.success('批量出库成功')
          this.handleQuery()
          this.loadStatistics()
        }).catch(err => {
          this.$message.error('批量出库失败：' + err.message)
        })
      }).catch(() => {
        this.$message.info('已取消批量出库')
      })
    },

    // 查看详情
    handleViewDetail(row) {
      this.$router.push({
        path: '/storage/finishStore/qmsDocument',
        query: {
          billsId: row.billsID,
          viewOnly: true
        }
      })
    },

    // 打印出库单
    handlePrint(row) {
      this.$message.info('打印功能开发中...')
      // TODO: 实现打印功能
    },

    // 页大小变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize
      this.pageNum = 1
      this.handleQuery()
    },

    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage
      this.handleQuery()
    }
  }
}
</script>

<style scoped>
.mt20 {
  margin-top: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-item {
  text-align: center;
  padding: 10px 0;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-value.pending {
  color: #E6A23C;
}

.stat-value.completed {
  color: #67C23A;
}

.stat-value.exception {
  color: #F56C6C;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}
</style>
